<?php
/**
 * 日志管理控制器
 */
class LogController extends App_Zend_Controller_Action_Admin
{
	/**该方法主要进行的是权限判断*/
	public function init() 
	{
		$user = App_User::getCurrentUser();
		if($user){
			if(!in_array('2', json_decode($user->permission))){
				exit('You have no priviage');
			}
		}else{
			$this->_redirect('/user/login');
		}
		parent::init();		
	}
	
	/**查看订单日志详情*/
	public function indexAction()
	{
		$id = $this->getRequest()->getParam('oid','');
		$site = $this->getRequest()->getParam('site','');
		$log = App_Model::factory('StockLog');//网站订单日志模型
		$sortlog = App_Model::factory('OrderSortLog');//订单分拣日志表
		$packlog = App_Model::factory('StockExportLog');//获取打包日志getStockExportLog
        $stock = App_Model::factory('Stock');
		
		$loglist = $log->getStockLog(array('order_id'=>$id,'site'=>$site))->toarray();
	    $sortloglist = $sortlog->getSortLog(array('order_id'=>$id,'site'=>$site,))->toarray();
		//先处理$loglist的$lv['info']可能出现重复的尺码的问题
		foreach ($loglist as $lk=>$lv){
			$linfo = json_decode($lv['info'], true);
			$vinfo = '';
			foreach($linfo as $v1){
				$vnum = 0;
				foreach ($linfo as $v2){
					if($v1[0] == $v2[0]){
						$vnum += $v2[1];
					}
				}
				$flag = true;
				foreach ($vinfo as $v3){
					if($v1[0] == $v3[0]){
						$flag = false;
					}
				}
				if($flag){
					$vinfo[] = array($v1[0],"$vnum");
				}
			}
			$loglist[$lk]['info']=json_encode($vinfo);
		}
			
		foreach($loglist as $k=>$v){
			$stockInfo=$stock->getBySku($v['sku']);
			if(!empty($stockInfo)){
				$loglist[$k]['title']=$stockInfo[0]['title'];
			}
			$flag = 0;
			$info = json_decode($v['info']);
			//计算每个订单项的缺货信息
			foreach ($sortloglist as $sl){
				if(trim($v['sku']) == trim($sl['sku'])){
					foreach ($info as &$sn){
						if($sn[0] == $sl['size']){
							$sn[1]-=1;
						}
					}
					$loglist[$k]['lack']=json_encode($info);
				}else{
					$flag += 1;
				}
			}
			if(!empty($sortloglist)){
				if(count($sortloglist) == $flag){
					$loglist[$k]['lack']=$v['info'];
				}
			}
		}
		
	    $packloglist = $packlog->getStockExportLog(array('order_id'=>$id,'site'=>$site,))->toarray();
	    foreach($loglist as $k=>$v){
	    	$stockInfo=$stock->getBySku($v['sku']);
	    	if(!empty($stockInfo)){
	    		$loglist[$k]['title']=$stockInfo[0]['title'];
	    	}
	    }

	    $ordermemo = App_Model::factory('OrderMemo');
		$memolist = $ordermemo->getMemoList(array('order_id'=>$id,'site'=>$site))->toarray();
	    
	    $this->view->id = $id;
	    $this->view->site = $site;
	    $this->view->logList = $loglist;
	    $this->view->sortloglist = $sortloglist;
	    $this->view->packloglist = $packloglist;
	    $this->view->memolist = $memolist;
	}

	/**订单修改*/
	public function omodifyAction()
	{
		$id = $this->getRequest()->getParam('oid','');
		$site = $this->getRequest()->getParam('site','');
		$log = App_Model::factory('StockLog');
		$sortlog = App_Model::factory('OrderSortLog');
        $stock = App_Model::factory('Stock');
		$stockvalue = App_Model::factory('StockValue');
        
		//如果该订单已经退货，则返回不能修改了
		$modify = true;
		$loglist = $log->getStockLog(array('order_id'=>$id,'site'=>$site))->toarray();
	    $sortloglist = $sortlog->getSortLog(array('order_id'=>$id,'site'=>$site,))->toarray();
		foreach ($loglist as $v){
			if($v['info_stock'] == 'add'){
				$modify = false;
			}
		}
		
		if($modify){
			//先处理$loglist的$lv['info']可能出现重复的尺码的问题
			foreach ($loglist as $lk=>$lv){
				$linfo = json_decode($lv['info'], true);
				$vinfo = '';
				foreach($linfo as $v1){
					$vnum = 0;
					foreach ($linfo as $v2){
						if($v1[0] == $v2[0]){
							$vnum += $v2[1];
						}
					}
					$flag = true;
					foreach ($vinfo as $v3){
						if($v1[0] == $v3[0]){
							$flag = false;
						}
					}
					if($flag){
						$vinfo[] = array($v1[0],"$vnum");
					}
				}
				$loglist[$lk]['info']=json_encode($vinfo);
			}
			
			foreach($loglist as $k=>$v){
				$stockInfo=$stock->getBySku($v['sku']);
				if(!empty($stockInfo)){
					$loglist[$k]['title']=$stockInfo[0]['title'];
				}
				$flag = 0;
				$info = json_decode($v['info']);
				//计算每个订单项的缺货信息
				foreach ($sortloglist as $sl){
					if(trim($v['sku']) == trim($sl['sku'])){
						foreach ($info as &$sn){
							if($sn[0] == $sl['size']){
								$sn[1]-=1;
							}
						}
						$loglist[$k]['lack']=json_encode($info);
					}else{
						$flag += 1;
					}
				}
				if(count($sortloglist) == $flag){
					$loglist[$k]['lack']=$v['info'];
				}
			}
			foreach($loglist as $k=>$v){
				$size = array();
				$stockvaluelist = $stockvalue->getBySku($v['sku'])->toArray();
				foreach ($stockvaluelist as $vv){
					$size[] = $vv['size'];
				}
				$loglist[$k]['size']=json_encode($size);
				$stockInfo=$stock->getBySku($v['sku']);
				if(!empty($stockInfo)){
					$loglist[$k]['title']=$stockInfo[0]['title'];
				}
			}
				
			$this->view->logList = $loglist;
			$this->view->id = $id;
			$this->view->site = $site;
			$this->view->msg = 'success';
		}else{
			$this->view->msg = 'fail';
		}
	}  
	
	/**保存订单修改*/
	public function domodifyAction()
	{
		$skus = $this->getRequest()->getParam('o_sku');//提交过来的所有SKU
		$oid = $this->getRequest()->getParam('o_id');
		$site = $this->getRequest()->getParam('site');
		$orderlog = App_Model::factory('StockLog');
		$loglist = $orderlog->getStockLog(array('order_id'=>$oid,'site'=>$site))->toarray();//修改前的订单项列表
		
		//$skus里面的值不能重复，否则不准修改
		if(empty($skus) || empty($oid) || empty($site) || empty($loglist)){
			$this->view->msg = 'fail';//修改失败
		}else if(count($skus) != count(array_unique($skus))){
			$this->view->msg = 'fail';//修改失败
		}else{
			$sortlog = App_Model::factory('OrderSortLog');
			$packlog = App_Model::factory('StockExportLog');
			$stockValue = App_Model::factory('StockValue');
			$modifylog = App_Model::factory('OrderModifyLog');

		    $db = App_Db::localDb();
		    $db->beginTransaction();
		    try {
		    	$o_info = array();//原来的订单信息
		    	$packloglist = $packlog->getStockExportLog(array('order_id'=>$oid,'site'=>$site))->toArray();
                //dump($loglist,false);
		    	//看看是否存在订单里某SKU是被删除了的
		    	foreach ($loglist as $ov){
		    		$flag = 0;
		    		$o_info[] = array('sku'=>$ov['sku'],'info'=>json_decode($ov['info']));
		    		foreach ($skus as $sku){
		    			if($ov['sku'] != $sku){
		    				$flag+=1;
		    			}
		    		}
		    		//遍历了所有提交的SKU都找不到说明该项的SKU被删除了
		    		if(count($skus) === $flag){
                        //dump('被删除的:'.$ov['sku'],false);
		    			$deleteSortLog = $sortlog->getSortLog(array('order_id'=>$oid,'site'=>$site,'sku'=>$ov['sku']))->toArray();//要删除的分拣项
		    			if(empty($deleteSortLog)){
		    				foreach (json_decode($ov['info']) as $ovi){
		    					$stockValue->addnum($ov['sku'],$ovi[0],$ovi[1]);//加回理论库存值
		    				}
		    			}else{
		    				foreach ($deleteSortLog as $dl){
		    					$sortlog->delete($dl['id']);//删除分拣了的项
		    					$stockValue->addnum($dl['sku'],$dl['size'],1);//加回理论库存值
		    					$stockValue->addtnum($dl['sku'],$dl['size'],1);//加回实际库存值
		    					//更新打包日志，若仅仅存在该SKU的包裹，则要删除打包项，否则就更新打包日志，去掉包含分拣项字段的对应该SKU的id
		    					if(!empty($packloglist)){
		    						foreach ($packloglist as $pv){
		    							$arr = array();
		    							$sortid = json_decode($pv['sort_ids']);
		    							foreach ($sortid as $sidk=>$sid){
		    								if($sid != $dl['id']){
		    									$arr[] = $sid;
		    								}
		    								if(empty($arr)){
		    									//删除该包裹
		    									$packlog->delete($pv['id']);
		    								}else{
		    									//更新该包裹
		    									$row = array('sort_ids'=>json_encode($arr));
		    									$packlog->update($row,$pv['id']);
		    								}
		    							}
		    						}
		    					}
		    				}
		    			}
		    			$orderlog->delete($ov['id']);//删除该SKU对应的订单项
		    		}
		    	}

		    	$n_info = array();//新的订单信息
		    	
		    	//针对新增了SKU的情况和在原SKU基础上进行修改的情况做处理
		    	foreach ($skus as $sku){
		    		$sizes = $this->getRequest()->getParam($sku.'-size');
		    		$nums = $this->getRequest()->getParam($sku.'-num');
		    		$flag = 0;
		    		$time = '';
		    		$sinfo = array();
		    		
		    		foreach ($sizes as $sk2=>$sv2){
		    			$sinfo[] = array($sv2,$nums[$sk2]);
		    		}
		    		$n_info[] = array('sku'=>$sku,'info'=>$sinfo);
		    		
		    		//将修改后提交过来的每一个sku都与原来订单的每一订单项进行对比，发现有改变的就修改，并检查是否存在有已分拣和已打包的，若存在则都要撤销
		    		foreach ($loglist as $oitem){
		    			$time = $oitem['add_time'];//获取订单下单的时间以便在新增SKU时取该时间值
		    			
		    			if($sku == $oitem['sku']){
		    				$inf = array();
		    				//这时候该sku订单项可能修改了也可能保持不变，所以需要对尺码size和num进行确认，不管如何都更新吧
		    				foreach ($sizes as $sk=>$sv){
		    					$inf[] = array(trim($sv),$nums[$sk]);
		    				}
		    				$row = array('info'=>json_encode($inf));
		    				//$orderlog->update2($row,$oitem['id'],$oitem['site'],$oitem['sku']);//更新订单项
		    				//删除已分拣的但现在被删除的尺码和数量
		    				//删除包裹项
		    			}else{
		    				$flag+=1;
		    			}
		    		}
		    	
		    		//如果找遍$loglist都找不到有对应的sku，那么就说这个$sku是新增的
		    		if(count($loglist) === $flag){
		    			$info = array();
		    			foreach ($sizes as $k2=>$v2){
		    				$info[] = array($v2,$nums[$k2]);
		    			    $stockValue->minusnum($sku,$v2,$nums[$k2]);//减去理论库存值
		    			}
		    			$row = array('add_time'=>$time,'sku'=>$sku,'site'=>$site,'info'=>json_encode($info), 'info_stock'=>'sub','order_id'=>$oid,'statu'=>'0');
                        //dump('新增的：'.$sku,false);
		    			$orderlog->add($row);
		    		}
		    	}
		    	
		    	//保存订单修改操作到订单修改记录
		    	$mrow = array('order_id'=>$oid,'site'=>$site,'o_info'=>json_encode($o_info),'n_info'=>json_encode($n_info),'add_time'=>date('Y-m-d H:i:s', time()),'add_user'=>$_SESSION['User']['user']['user_name']);
		    	$modifylog->add($mrow);
		    	
		    	$db->commit();
			    $msg = 'success';
		    } catch (Exception $e) {
			    $db->rollback();
			    $msg = 'fail';
		    }
		}

		$this->view->msg = $msg;
		$this->view->orderid = $oid;
		$this->view->site = $site;
	}
	
	/**订单修改日志*/
	public function modifylogAction()
	{
		$log = App_Model::factory('OrderModifyLog');
		
		$page = $this->getRequest()->getParam('page',1);
		$orderid = $this->getRequest()->getParam('orderid');
		$site = $this->getRequest()->getParam('site');
		$starttime = $this->getRequest()->getParam('starttime');
		$endtime = $this->getRequest()->getParam('endtime');
		
		/**根据条件获取StockLog模型集合，然后转换成数组*/
		$pageNum = 15;//每页显示条数
		$logList = $log->listAll($orderid,$site,$starttime,$endtime,$page, $pageNum)->toArray();

		/**将相应的值分配到视图调用*/
		$this->view->logList = $logList;
		$this->view->orderid = $orderid;
		$this->view->site = $site;
		$this->view->starttime = $starttime;
		$this->view->endtime = $endtime;
		
		/**生成分页对象*/
		$num = $log->getTotalNum($orderid,$site,$starttime,$endtime);
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($num));
		$paginator->setItemCountPerPage($pageNum);
		$paginator->setCurrentPageNumber($page);
		$this->view->paginator = $paginator ;
	}
	
	/**订单备注*/
	public function omemoAction()
	{
		$oid = $this->getRequest()->getParam('oid');
		$site = $this->getRequest()->getParam('site');
		$is_memo = $this->getRequest()->getParam('is_memo', 0);
		
		$orderlog = App_Model::factory('StockLog');
		$ordermemo = App_Model::factory('OrderMemo');
		
		if($this->getRequest()->isPost()) {
			$memo = $this->getRequest()->getParam('memo');
			if(empty($memo)){
				$this->view->msg = '备注不能为空';
			}else{
				$is_memo = $is_memo?$is_memo:'1';
				$orderlog->update(array('is_memo'=>$is_memo,'memo'=>$memo), $oid, $site);
				$ordermemo->add(array('order_id'=>$oid,'site'=>$site, 'memo'=>$memo, 'add_time'=>date('Y-m-d H:i:s', time()), 'add_user'=>$_SESSION['User']['user']['user_name']));
			}
		}
		
		$loglist = $orderlog->getStockLog(array('order_id'=>$oid,'site'=>$site))->toarray();
		$memolist = $ordermemo->getMemoList(array('order_id'=>$oid,'site'=>$site))->toarray();
		$this->view->oid = $oid;
		$this->view->site = $site;
		$this->view->loglist = $loglist;
		$this->view->memolist = $memolist;
	}
	
	/**进库扫描*/
	public function scanimportAction()
	{
		$msg = $this->getRequest()->getParam('msg');
		$this->view->msg = $msg;
	}
	
	/**出库扫描*/
	public function scanoutAction()
	{
		$msg = $this->getRequest()->getParam('msg');
		$this->view->msg = $msg;
	}
	
	/**分拣中心扫描*/
	public function scanexportAction()
	{
		$id = $this->getRequest()->getParam('order_id','');
		$site = $this->getRequest()->getParam('site','');
		
		$log = App_Model::factory('StockLog');//网站订单日志模型
		$sortlog = App_Model::factory('OrderSortLog');//订单分拣日志表
        $stock = App_Model::factory('Stock');
		if(empty($id)||empty($site)){
			$this->view->scanByOrder = 'no';
		}else{
			$this->view->scanByOrder = 'yes';//是否是通过订单进行分拣扫描
			$this->view->site = $site;
			$this->view->oid = $id;
			$loglist = $log->getStockLog(array('order_id'=>$id,'site'=>$site))->toarray();
	    	$sortloglist = $sortlog->getSortLog(array('order_id'=>$id,'site'=>$site,))->toarray();
			if(count($loglist)){//通过count判断数组有没有内容
				//先处理$loglist的$lv['info']可能出现重复的尺码的问题
				foreach ($loglist as $lk=>$lv){
					$linfo = json_decode($lv['info'], true);
					$vinfo = '';
					foreach($linfo as $v1){
						$vnum = 0;
						foreach ($linfo as $v2){
							if($v1[0] == $v2[0]){
								$vnum += $v2[1];
							}
						}
						$flag = true;
						foreach ($vinfo as $v3){
							if($v1[0] == $v3[0]){
								$flag = false;
							}
						}
						if($flag){
							$vinfo[] = array($v1[0],"$vnum");
						}
					}
					$loglist[$lk]['info']=json_encode($vinfo);
				}
				
				foreach($loglist as $k=>$v){
					$stockInfo=$stock->getBySku($v['sku']);
					if(!empty($stockInfo)){
						$loglist[$k]['title']=$stockInfo[0]['title'];
					}
					$flag = 0;
					$info = json_decode($v['info']);
					//计算每个订单项的缺货信息
					foreach ($sortloglist as $sl){
						if(trim($v['sku']) == trim($sl['sku'])){
							foreach ($info as &$sn){
								if($sn[0] == $sl['size']){
									$sn[1]-=1;
								}
							}
							$loglist[$k]['lack']=json_encode($info);
						}else{
							$flag += 1;
						}
					}
					if(count($sortloglist) == $flag){
						$loglist[$k]['lack']=$v['info']; 
					}
				}
				$this->view->logList = $loglist;
			}else{
				$msg = '查找不到指定订单号与网站的日志，请返回网站订单日志确认！';
				$this->view->msg = $msg;
			}
		}
	}

	/**库存量变化日志*/
	public function numlogAction()
	{
		/**建立进库日志表StockNumlog模型*/
		$log = App_Model::factory('StockNumlog');
	
		$page = $this->getRequest()->getParam('page',1);
		$isspecial = $this->getRequest()->getParam('isspecial','0');
		$starttime = $this->getRequest()->getParam('starttime','');
		$endtime = $this->getRequest()->getParam('endtime','');
	
		$pageNum = 10;//每页显示条数
		$logList = $log->listAll(0,'',$starttime,$endtime,$page, $pageNum);
	
		$this->view->logList = $logList;
		$this->view->starttime = $starttime;
		$this->view->endtime = $endtime;
	
		$num = $log->getTotalNum(0,'',$starttime,$endtime);
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($num));
		$paginator->setItemCountPerPage($pageNum);
		$paginator->setCurrentPageNumber($page);
		$this->view->paginator = $paginator ;
	}
	
	/**网站订单日志*/
	public function orderAction()
	{
		/**建立网站订单日志表StockLog和库存表Stock模型*/
        $log = App_Model::factory('StockLog');
        $stock = App_Model::factory('Stock');
        
        $page = $this->getRequest()->getParam('page',1);
        $orderid = $this->getRequest()->getParam('orderid');
        $sku = $this->getRequest()->getParam('sku');
        $statu = $this->getRequest()->getParam('statu','');
        $infostock = $this->getRequest()->getParam('info_stock','sub');
        $ismemo = $this->getRequest()->getParam('is_memo');
        $site = $this->getRequest()->getParam('site');
        $starttime = $this->getRequest()->getParam('starttime');
        $endtime = $this->getRequest()->getParam('endtime');
        
        /**根据条件获取StockLog模型集合，然后转换成数组*/
        $pageNum = 15;//每页显示条数
       	$logList = $log->listAll($orderid,$sku,$statu,$infostock,$ismemo,$site,$starttime,$endtime,$page, $pageNum);
        $logList=$logList->toArray();
        //dump($logList);
        foreach($logList as $k=>$v){
        	$stockInfo=array();
        	$stockInfo=$stock->getBySku($v['sku']);
        	if(!empty($stockInfo)){
        		$logList[$k]['title']=$stockInfo[0]['title'];
        	}
        }
        /**将相应的值分配到视图调用*/
       	$this->view->logList = $logList;
        $this->view->orderid = $orderid;
        $this->view->sku = $sku;
        $this->view->site = $site;
        $this->view->statu = $statu;
        $this->view->infostock = $infostock;
        $this->view->ismemo = $ismemo;
        $this->view->starttime = $starttime;
        $this->view->endtime = $endtime;
        
        /**生成分页对象*/
		$num = $log->getTotalNum($orderid,$sku,$statu,$infostock,$ismemo,$site,$starttime,$endtime);
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($num));
        $paginator->setItemCountPerPage($pageNum);
        $paginator->setCurrentPageNumber($page); 
        $this->view->paginator = $paginator ;
	}
	
	/**处理网站订单的退货*/
	public function returnorderAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
        $id = $this->getRequest()->getParam('id',0);
		$id = intval($id);
        if($id!=0){
        	$stocklog = App_Model::factory('StockLog');
        	$ordersortlog = App_Model::factory('OrderSortLog');
			$stockvalue = App_Model::factory('StockValue');
        		
        	$db = App_Db::localDb();
        	$db->beginTransaction();
        	try {
        		$order = $stocklog->getOne($id)->toArray();
        		$stocklog->update(array('statu'=>5),$order['order_id'],$order['site']);
        		$oslist = $ordersortlog->getSortLog(array('order_id'=>$order['order_id'],'site'=>$order['site']))->toArray();
        		foreach ($oslist as $v){
        			//删除分拣项，加回库存实际值
        			$ordersortlog->delete($v['id']);
					$stockvalue->addtnum($v['sku'],$v['size'],1);//增加实际库存
					//$stockvalue->addnum($v['sku'],$v['size'],1);//增加理论库存，但这个用户订单退货时已经在update.php接口加回了
        		}
        		$db->commit();
        		echo 1;
        	} catch (Exception $e) {
        		$db->rollback();
        		echo 0;
        	}
        }
	}
	
	/**出库日志*/
	public function exportAction()
	{
		$log = App_Model::factory('StockExportLog');
		$stock = App_Model::factory('Stock');
	
		/**取出搜索表单或者分页链接提交过来的数据*/
		$page = $this->getRequest()->getParam('page',1);
		$billid = $this->getRequest()->getParam('billid');
		$sku = $this->getRequest()->getParam('sku','');
		$site = $this->getRequest()->getParam('site','');
		$starttime = $this->getRequest()->getParam('starttime');
		$endtime = $this->getRequest()->getParam('endtime');
	
		/**根据条件获取StockExportLog模型集合，然后转换成数组*/
		$pageNum = 10;//每页显示条数
		$logList = $log->listAll($billid,$sku,$site,$starttime,$endtime,$page,$pageNum);
		$logList=$logList->toArray();
		foreach($logList as $k=>$v){
			$stockInfo=array();
			$stockInfo=$stock->getBySku($v['sku']);
			if(!empty($stockInfo)){
				$logList[$k]['title']=$stockInfo[0]['title'];//为数据集增加标题名称
			}
		}
		
		/**将相应的值分配到视图调用*/
		$this->view->logList = $logList;
		$this->view->billid = $billid;
		$this->view->sku = $sku;
		$this->view->site = $site;
		$this->view->starttime = $starttime;
		$this->view->endtime = $endtime;
	
		/**生成分页对象*/
		$num = $log->getTotalNum($billid,$sku,$site,$starttime,$endtime);
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($num));
		$paginator->setItemCountPerPage($pageNum);
		$paginator->setCurrentPageNumber($page);
		$this->view->paginator = $paginator ;
	}
	
	/**特殊库管日志*/
	public function specialAction()
	{
		/**建立进库日志表StockNumlog模型*/
		$log = App_Model::factory('StockNumlog');
		
		$page = $this->getRequest()->getParam('page',1);
		$starttime = $this->getRequest()->getParam('starttime','');
		$endtime = $this->getRequest()->getParam('endtime','');
		$ischeck = $this->getRequest()->getParam('ischeck',false);//待审核的状态：0待审核，1已审核，2已否决

		/**根据条件获取StockNumLog模型集合*/
		$pageNum = 10;
		$logList = $log->listAll(1,$ischeck,$starttime,$endtime,$page, $pageNum);
		
		$num = $log->getTotalNum(1,$ischeck,$starttime,$endtime);
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($num));
		$paginator->setItemCountPerPage($pageNum);
		$paginator->setCurrentPageNumber($page);
		
		$this->view->logList = $logList;
		$this->view->paginator = $paginator ;
		$this->view->starttime=$starttime;
		$this->view->endtime=$endtime;
		$this->view->ischeck=$ischeck;
	}

	/**进库扫描或者打包扫描的时候，根据sku值异步返回页面关于对应的stock信息*/
	public function imloadstockAction()
	{
		//禁用视图渲染与布局以便能够ajax向原页面echo输出需要返回的值，否则会提示找不到log/imloadstock.phtml文件
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		$cpModel = App_Model::factory('StockCategoryPrice');
		$stockModel =  App_Model::factory('Stock');
		$stockvalue = App_Model::factory('StockValue');
		
		$barcode = $this->getRequest()->getParam('code', '');//条形码
		$skuid = intval(substr($barcode,0,5));
		$sku = trim($stockModel->getOne($skuid)->sku);
		preg_match('/([A-Z]+)/',$sku,$matches);
		if(!empty($matches[1])){
			$row = $cpModel->getByShortsku($matches[1])->toArray();
		}
		$sizeid = substr($barcode,5,-4);//根据条形码提取尺码
		
		/**获取对应sku码的库存信息*/
		$stock = $stockModel->getBySku($sku)->toArray();
		$stvalue = $stockvalue->getById($sizeid);
		
		/**生成异步返回的内容*/
		$t=date('Y-m-d H:i:s',time());
		$content = "<tr><td><input type='text' hidden='hidden' name='barcode[]' value='".$barcode."'>".
				   "<input type='checkbox' name='isadd[]'>操作</td><td><input type='text' hidden='hidden' name='sku[]' value='".$sku."'>".$sku."</td><td>".
		           $stock[0]['title']."<input type='text' hidden='hidden' name='title[]' value='".$stock[0]['title']."'></td><td>".
                   "尺码: ".$stvalue->size.", 数量: 1<br><input type='text' hidden='hidden' name='size[]' value='".$stvalue->size."'></td><td>".
                   "<input type='text' size='6' name='c_price[]' class='form-control' readonly='readonly' value='".$row[0]['price']."'>".
                   "</td><td><input type='text' size='6' name='m_price[]' class='form-control' readonly='readonly' value='".$row[0]['b_price']."'></td>".
                   "<td>".$t."<input type='text' hidden='hidden' name='addtime[]' value='".$t."'></td><td>".$_SESSION['User']['user']['user_name'].
		           "<input type='text' hidden='hidden' name='adduser[]' value='".$_SESSION['User']['user']['user_name']."'></td></tr>";
		echo json_encode(array('content'=>$content,'size'=>$stvalue->size,'sku'=>$sku));
	}
	
	/**分拣中心扫描的时候，根据sku值异步返回页面关于对应的stock信息*/
	public function exloadstockAction()
	{
		//禁用视图渲染与布局以便能够ajax向原页面echo输出需要返回的值，否则会提示找不到log/exoadstock.phtml文件
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		$cpModel = App_Model::factory('StockCategoryPrice');
		$stockModel =  App_Model::factory('Stock');
		$stockvalue = App_Model::factory('StockValue');
		
		$barcode = $this->getRequest()->getParam('code', '');//条形码
		$skuid = intval(substr($barcode,0,5));
		$sku = trim($stockModel->getOne($skuid)->sku);
		preg_match('/([A-Z]+)/',$sku,$matches);
		if(!empty($matches[1])){
			$row = $cpModel->getByShortsku($matches[1])->toArray();
		}
		$sizeid = substr($barcode,5,-4);//根据条形码提取尺码
		
		/**获取对应sku码的库存信息*/
		$stock = $stockModel->getBySku($sku)->toArray();
		$stvalue = $stockvalue->getById($sizeid);
		
		/**生成异步返回的内容*/
		$t=date('Y-m-d H:i:s',time());
		$content = "<tr><td><input type='text' hidden='hidden' name='barcode[]' value='".$barcode."'>".
				"<input type='checkbox' name='issort[]'>分拣</td><td><input type='text' hidden='hidden' name='sku[]' value='".$sku."'>".$sku."</td><td>".
				$stock[0]['title']."<input type='text' hidden='hidden' name='title[]' value='".$stock[0]['title']."'></td><td>".
				"尺码: ".$stvalue->size.", 数量: 1<br><input type='text' hidden='hidden' name='size[]' value='".$stvalue->size."'></td><td>".
				"<input type='text' size='6' name='c_price[]' class='form-control' readonly='readonly' value='".$row[0]['price']."'>".
				"</td><td><input type='text' size='6' name='m_price[]' class='form-control' readonly='readonly' value='".$row[0]['b_price']."'></td><td><select name='isgift[]'><option value='0'>否</option><option value='1'>是</option></select></td>".
				"<td>".$t."<input type='text' hidden='hidden' name='addtime[]' value='".$t."'></td><td>".$_SESSION['User']['user']['user_name'].
				"<input type='text' hidden='hidden' name='adduser[]' value='".$_SESSION['User']['user']['user_name']."'></td></tr>";
		echo json_encode(array('content'=>$content,'size'=>$stvalue->size,'sku'=>$sku));
	}
	
	/**修改订单时异步增加sku*/
	public function modifyaddAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$sku = $this->getRequest()->getParam('n_sku', '');
		$stockModel =  App_Model::factory('Stock');
		$stockvalue = App_Model::factory('StockValue');
		$stock = $stockModel->getBySku($sku)->toArray();
		
		$stockvaluelist = $stockvalue->getBySku($sku)->toArray();
		$str = "<div>尺码：<select class='form-control' name='".$sku."-size[]'>";
		foreach ($stockvaluelist as $vv){
			$str = $str."<option value='".$vv['size']."'>".$vv['size']."</option>";
		}
		$str = $str."</select>&nbsp;&nbsp;&nbsp;&nbsp;数量：<input name='".$sku."-num[]' class='form-control small' type='text' value='1'>"."<a class='delete-sn'>删除</a></div></div></td><td>";
		
		$content = "";
		if(empty($stock)){
			echo json_encode(array('content'=>$content,'flag'=>'fail'));
		}else{
			$content = "<tr id='".$sku."'><td class='sku'>".$sku."<input type='text' hidden='hidden' name='o_sku[]' value='".$sku."'></td><td>".$stock[0]['title'].
			    "</td><td class='size'><div class='after-save hidden'></div><div class='after-edit form-inline'>".$str.
                date('Y-m-d H:i:s',time())."</td><td><span class='status label label-warning'>未分拣、未处理</span></td><td>".
                "<a class='edit hidden'>修改</a><a class='save'>确认</a><br><a class='add-size'>加码</a></td></tr>";
			echo json_encode(array('content'=>$content,'flag'=>'success'));
		}
	}
	
	/**全缺货登记*/
	public function alloutstockAction()
	{
		$orderid = $this->getRequest()->getParam('orderid');
		$site = $this->getRequest()->getParam('site');
		if(empty($orderid) || empty($site)){
			$msg = 'fail';
		}
		
		//分拣过的不能进行全缺货登记
		$sortlog = App_Model::factory('OrderSortLog');//订单分拣日志表
		$sortloglist = $sortlog->getSortLog(array('order_id'=>$orderid,'site'=>$site,))->toarray();
		
		if(empty($msg) && empty($sortloglist)){
			$stockLog = App_Model::factory('StockLog');//网站订单日志表，要改变状态

			$db = App_Db::localDb();
			$db->beginTransaction();
			try {
				$stockLog->update(array('statu'=>1,),$orderid,$site);//分拣中，缺货中
				$db->commit();
				$msg = 'success';
			} catch (Exception $e) {
				$db->rollback();
				$msg = 'fail';
			}
		}else{
			$msg = 'fail';
		}
		$this->view->msg=$msg;
	}
	
	/**在分拣中心扫描后进行的保存分拣操作*/
	public function scansortAction()
	{
		/**禁用视图和布局以便可以echo输出内容*/
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		$sortlog = App_Model::factory('OrderSortLog');//订单分拣日志表
		$stockLog = App_Model::factory('StockLog');//网站订单日志表，要改变状态
		$stockValue = App_Model::factory('StockValue');//新建包含库存尺码数量值表的模型，要减库存值

		$orderid = $this->getRequest()->getParam('orderid');
		$site = $this->getRequest()->getParam('site');
		if(empty($orderid) || empty($site)){
			$msg = 'fail';
		}
		
		if(empty($msg)) {
	    	$isArr = $this->getRequest()->getParam('issort');//是否要分拣
		    $isgift = $this->getRequest()->getParam('isgift');
	    	$sku = $this->getRequest()->getParam('sku');
	    	$title = $this->getRequest()->getParam('title');
	    	$size = $this->getRequest()->getParam('size');
	    	$cprice = $this->getRequest()->getParam('c_price');
	    	$mprice = $this->getRequest()->getParam('m_price');
	    	$addtime = $this->getRequest()->getParam('addtime');
	    	
	    	$sortloglist = $sortlog->getSortLog(array('order_id'=>$orderid,'site'=>$site,))->toarray();
	    	
	    	//下面要取出订单的sku和size并各自合并成2个数组并做处理
	    	$o_sls = array();
	    	if(empty($sortloglist)){//未分拣过的
	    		$stockloglist = array_merge($stockLog->getStockLog(array('order_id'=>$orderid,'site'=>$site,'statu'=>0))->toarray(),$stockLog->getStockLog(array('order_id'=>$orderid,'site'=>$site,'statu'=>1))->toarray());
	    		//先处理$stockloglist的$lv['info']可能出现重复的尺码的问题
	    		foreach ($stockloglist as $lk=>$lv){
	    			$linfo = json_decode($lv['info'], true);
	    			$vinfo = '';
	    			foreach($linfo as $v1){
	    				$vnum = 0;
	    				foreach ($linfo as $v2){
	    					if($v1[0] == $v2[0]){
	    						$vnum += $v2[1];
	    					}
	    				}
	    				$flag = true;
	    				foreach ($vinfo as $v3){
	    					if($v1[0] == $v3[0]){
	    						$flag = false;
	    					}
	    				}
	    				if($flag){
	    					$vinfo[] = array($v1[0],"$vnum");
	    				}
	    			}
	    			$stockloglist[$lk]['info']=json_encode($vinfo);
	    		}
	    		
	    		foreach ($stockloglist as $sl){
	    			foreach (json_decode($sl['info']) as $v){
	    				$o_sls[] = json_encode(array('sku'=>$sl['sku'],'size'=>$v));
	    			}
	    		}
	    	}else{//分拣了部分，缺货
	    		$stockloglist = $stockLog->getStockLog(array('order_id'=>$orderid,'site'=>$site,'statu'=>1))->toarray();
	    		//先处理$stockloglist的$lv['info']可能出现重复的尺码的问题
	    		foreach ($stockloglist as $lk=>$lv){
	    			$linfo = json_decode($lv['info'], true);
	    			$vinfo = '';
	    			foreach($linfo as $v1){
	    				$vnum = 0;
	    				foreach ($linfo as $v2){
	    					if($v1[0] == $v2[0]){
	    						$vnum += $v2[1];
	    					}
	    				}
	    				$flag = true;
	    				foreach ($vinfo as $v3){
	    					if($v1[0] == $v3[0]){
	    						$flag = false;
	    					}
	    				}
	    				if($flag){
	    					$vinfo[] = array($v1[0],"$vnum");
	    				}
	    			}
	    			$stockloglist[$lk]['info']=json_encode($vinfo);
	    		}

	    		$s_sls = array();//取出分拣的sku和size并各自合并成2个数组
	    		foreach ($sortloglist as $sl){
	    			$s_sls[] = json_encode(array('sku'=>trim($sl['sku']),'size'=>$sl['size']));
	    		}
	    		$s_sls = array_count_values($s_sls);//已分拣的信息集
	    		foreach ($s_sls as $sk => $snum){
	    			foreach ($stockloglist as &$sls){
	    				if(trim($sls['sku']) == json_decode($sk)->sku){//sku要相等
	    					$info =array();//重组$sls的info内容
	    					//dump(json_decode($sk)->sku,false);dump(json_decode($sk)->size,false);dump($snum,false);dump($sls['info'],false);
	    					foreach (json_decode($sls['info']) as $sv){
	    						if($sv[0] == json_decode($sk)->size){//size要相等
	    							$snum = $sv[1]-$snum;
	    							if($snum>0){//$snum为0说明该sku下的该尺码已经分拣完成，无需理会
	    								$info[] = array(json_decode($sk)->size,"$snum");
	    							}
	    						}else{
	    							$info[] = $sv;
	    						}
	    					}
	    					if(!empty($info)){
	    						$sls['info'] = json_encode($info);//重组$sls的info内容
	    					}
	    				}
	    			}
	    		}
	    		foreach ($stockloglist as $sl){
	    			foreach (json_decode($sl['info']) as $v){
	    				$o_sls[] = json_encode(array('sku'=>$sl['sku'],'size'=>$v));
	    			}
	    		}
	    	}
	    	
	    	/**整理提交的扫描信息*/
	    	$sls = array();
	    	foreach ($isArr as $ik){
	    		$sls[] = json_encode(array($sku[$ik],$size[$ik]));
	    	}
	    	$sls = array_count_values($sls);//统计数组中所有值出现的次数
	    	$p_sls = array();
	    	foreach ($sls as $sk => $num){
	    		$skusize = json_decode($sk);
	    		foreach ($o_sls as $vv){
	    			//假如多分拣了某件商品
	    			if($skusize[0]==json_decode($vv)->sku && $skusize[1]==json_decode($vv)->size[0] && json_decode($vv)->size[1]<$num){
	    				$num = json_decode($vv)->size[1];
	    			}
	    		}
	    		$p_sls[] = json_encode(array('sku'=>$skusize[0],'size'=>array($skusize[1],"$num")));
	    	}
	    	$outstock = array_diff($o_sls,$p_sls);//该交集数组$o_sls-$p_sls为空时说明不缺货，否则缺货信息集就是$outstock
	    	
		    $db = App_Db::localDb();
		    $db->beginTransaction();
	    	if(!empty($isArr)){
			    try {
			    	foreach($isArr as $k){
				    	$data = array(
							'order_id'=>$orderid,
							'site'=>$site,
							'sku'=>trim($sku[$k]),
							'title'=>$title[$k],
							'size'=>trim($size[$k]),
							'add_time'=>$addtime[$k],
							'adduser'=>$_SESSION['User']['user']['user_name'],
					 		'isgift'=>intval($isgift[$k]),
				    		'statu'=>0,);
				    	$sortlog->add($data);//新增订单分拣日志
				    	$stockValue->minustnum($sku[$k],$size[$k],1);//减实际库存值
			    	}
			    	//更新网站订单状态
			    	$stlist = array_merge($stockLog->getStockLog(array('order_id'=>$orderid,'site'=>$site,'statu'=>0))->toarray(),$stockLog->getStockLog(array('order_id'=>$orderid,'site'=>$site,'statu'=>1))->toarray());
			    	if(empty($outstock)){//不缺货
			    		foreach ($stlist as $stl){
			    		    $sl = $sortlog->getSortLog(array('order_id'=>$orderid,'site'=>$site,'statu'=>2,'sku'=>$stl['sku']))->toarray();
			    			if(empty($sl[0])){
			    				$stockLog->update2(array('statu'=>2,),$orderid,$site,$stl['sku']);
			    			}else{
			    				$stockLog->update2(array('statu'=>3,),$orderid,$site,$stl['sku']);
			    			}
			    		}
			    	}else{
			    		foreach ($stlist as $stl){
			    			$fl = false;
			    			$sl = $sortlog->getSortLog(array('order_id'=>$orderid,'site'=>$site,'statu'=>2,'sku'=>$stl['sku']))->toarray();
			    			foreach ($outstock as $osl){
			    				if($stl['sku'] == json_decode($osl)->sku){
			    					$fl = true;
			    				}
			    			}
			    			if($fl){
			    				$stockLog->update2(array('statu'=>1,),$orderid,$site,$stl['sku']);
			    			}else{
			    				if(empty($sl[0])){
			    					$stockLog->update2(array('statu'=>2,),$orderid,$site,$stl['sku']);
			    				}else{
			    					$stockLog->update2(array('statu'=>3,),$orderid,$site,$stl['sku']);
			    				}
			    			}
			    		}
			    	}
			    	$db->commit();
			    	$msg = 'success';
		    	} catch (Exception $e) {
			    	$db->rollback();
			    	$msg = 'fail';
		    	}
		    }
	   	}
	   	
        $this->_redirect('/log/opersort/oid/'.$orderid.'/site/'.$site.'/msg/'.$msg);
	}
	
	/**操作做了分拣操作的订单*/
	public function opersortAction()
	{
		$orderid = $this->getRequest()->getParam('oid');
	    $site = $this->getRequest()->getParam('site');
	    $msg = $this->getRequest()->getParam('msg','');
	    
	    $log = App_Model::factory('StockLog');//网站订单日志模型
	    $stock = App_Model::factory('Stock');
	    $loglist = $log->getStockLog(array('order_id'=>$orderid,'site'=>$site))->toarray();
	    if(count($loglist)){//通过count判断数组有没有内容
	    	foreach($loglist as $k=>$v){
	    		$stockInfo=array();
	    		$stockInfo=$stock->getBySku($v['sku']);
	    		if(!empty($stockInfo)){
	    			$loglist[$k]['title']=$stockInfo[0]['title'];
	    		}
	    	}
	    }
	    
	    $sortlog = App_Model::factory('OrderSortLog');//订单分拣日志模型
	    $sortloglist = $sortlog->getSortLog(array('order_id'=>$orderid,'site'=>$site,))->toarray();
	    
		$this->view->loglist=$loglist;
		$this->view->sortloglist=$sortloglist;
		$this->view->orderid=$orderid;
		$this->view->site=$site;
		$this->view->msg=$msg;
	}
	
	/**删除分拣项的操作*/
	public function deletesortAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		$sort_id = $this->getRequest()->getParam('id', 0);
		$sort_id = intval($sort_id);
		if($sort_id!=0){
			$stocklogModel = App_Model::factory('StockLog');
			$stockvalueModel = App_Model::factory('StockValue');
			$sortlogModel = App_Model::factory('OrderSortLog');
			$sortlog = $sortlogModel->getById($sort_id)->toArray();
			
			//检查删除该分拣项之后对应的订单项是否缺货
			$sortloglist = $sortlogModel->getSortLog(array('order_id'=>$sortlog['order_id'],'site'=>$sortlog['site'],'sku'=>$sortlog['sku'],'size'=>$sortlog['size']))->toArray();
			$stockloglist = $stocklogModel->getStockLog(array('order_id'=>$sortlog['order_id'],'site'=>$sortlog['site'],'sku'=>$sortlog['sku']))->toArray();
			
			$flag = false;
			$sl = array();
			foreach ($sortloglist as $v){
				$sl[] = $v['size'];
			}
			$sl = array_count_values($sl);
			
			foreach (json_decode($stockloglist[0]['info']) as $size){
				if(!empty($sl[$size[0]])){
					if($sl[$size[0]]-1 < $size[1]){
					    $flag = true;
					}
				}
			}
			
			$db = App_Db::localDb();
			$db->beginTransaction();
			try {
				$sortlogModel->delete($sort_id);//删除分拣项
		    	$stockvalueModel->addtnum($sortlog['sku'],$sortlog['size'],1);//加回实际库存值
				if($flag){
					$stocklogModel->update2(array('statu'=>1),$sortlog['order_id'],$sortlog['site'],$sortlog['sku']);//更新对应的订单对应的SKU为缺货中状态
				}
				$db->commit();
				echo 1;
			} catch (Exception $e) {
				$db->rollback();
				echo 0;
			}
		}
	}
	
	/**对进行过分拣的订单进行打包操作*/
	public function packAction()
	{
		$orderid = $this->getRequest()->getParam('orderid');
	    $site = $this->getRequest()->getParam('site');
	    $billid = $this->getRequest()->getParam('billid');//快递单号
		$sku = $this->getRequest()->getParam('sku');//提交过来可能要打包的sku
		$size = $this->getRequest()->getParam('size');//提交过来可能要打包的size
		$isArr = $this->getRequest()->getParam('isadd');//是否要打包
	    $addtime = $this->getRequest()->getParam('addtime');
	    $memo = $this->getRequest()->getParam('memo');//印号
	    $weight = $this->getRequest()->getParam('weight','');//重量
	    $country = $this->getRequest()->getParam('country','');//国家
	    $piece = $this->getRequest()->getParam('piece','');//国家
	    
		$msg = array();
		if(empty($billid)){
			$msg[] = '请确认快递单号已填写';
		}
		if(empty($orderid) || empty($site)){
			$msg[] = '订单号或者网站检测到错误，请重新打包';
		}	
		if(!empty($memo)){
			$temp = '';
			foreach ($memo as $m){
				$temp = $temp.$m.';';
			}
			$memo = $temp;
		}
		
		if(empty($msg)){
			/**已打包的分拣不能打包，扫描错的也不可以打包，只有未处理和已操作的分拣才可以打包*/
			$sortlog = App_Model::factory('OrderSortLog');//订单分拣日志模型
			/**取出状态为0或者为1的项，即未处理的项或者已操作*/
			$sortloglist =array_merge($sortlog->getSortLog(array('order_id'=>$orderid,'site'=>$site,'statu'=>0))->toarray(), $sortlog->getSortLog(array('order_id'=>$orderid,'site'=>$site,'statu'=>1))->toarray());
			$packid = array();//存放打包扫描正确的项对应的订单分拣日志id
			$packsku = array();//存放打包扫描正确的项对应的订单分拣日志sku
			$tempSortloglist = $sortloglist;
			$counter = 0;//计数器，用来计数判别是否有提交错误的扫描项
			foreach($isArr as $k){
				/**获取要进行打包的分拣id*/
				foreach ($sortloglist as $key => $sort){
					if(($sku[$k] == $sort['sku']) && ($size[$k] == $sort['size'])){
						$packid[] = $sort['id'];
						$packsku[] = $sort['sku'];
						unset($sortloglist[$key]);//要删除数组项是因为可能存在的已分拣项都是同一sku和id的
						break;
					}
				}
				/**看看是否有提交错误的扫描项，这些项是不能打包的*/
				foreach ($tempSortloglist as $sort2){
					if(!($sku[$k]==$sort2['sku'] && $size[$k]==$sort2['size'])){
						$counter += 1;
					}
				}
				if($counter == count($tempSortloglist)){
					$error = '打包失败，存在错误的扫描项，请检查并重新扫描';
				}
				$counter = 0;//计数器归0
			}
		}
		
		if (!empty($error)){
			$msg[] = $error;
		}
		
		/**如果存在错误，打包不成功*/
		if(empty($msg)){
			$packlog = App_Model::factory('StockExportLog');//打包日志、实际出库日志模型
			$db = App_Db::localDb();
			$db->beginTransaction();
			try {
				foreach ($packid as $pk=>$id){
					$row = array('pack_time'=>$addtime[$k],'packuser'=>$_SESSION['User']['user']['user_name'],'statu'=>'2',);//状态1为已打包
					$sortlog->update($row, $id);//更新订单分拣日志
				}
				/**新增打包日志：存放快递单号，绑定的状态为2的订单分拣日志*/
				$data = array(
						'bill_id'=>$billid,
						'sort_ids'=>json_encode($packid),
						'order_id'=>$orderid,
						'site'=>$site,
						'memo'=>$memo,
						'weight'=>$weight,
						'country'=>$country,
						'piece'=>$piece,
						'add_time'=>date('Y-m-d H:i:s', time()),
						'adduser'=>$_SESSION['User']['user']['user_name'],
				);
				$packlog->add($data);
				$db->commit();
				$this->view->ms='success';
			} catch (Exception $e) {
				$db->rollback();
				$this->view->ms='fail';
			}
			
			/**打包成功就要执行修改网站订单日志的状态了,判断应该赋予的状态：是否为4分拣完、处理完*/
			if($this->view->ms == 'success'){
			    $stocklog = App_Model::factory('StockLog');//网站订单日志模型
				$loglist = $stocklog->getStockLog(array('order_id'=>$orderid,'site'=>$site))->toarray();
				$s_sls = array();
				$o_sls = array();

				$sortloglist2 = $sortlog->getSortLog(array('order_id'=>$orderid,'site'=>$site,'statu'=>2))->toarray();//取出状态为2的项，即已打包的项
				foreach ($sortloglist2 as $sl){
					$s_sls[] = json_encode(array('sku'=>$sl['sku'],'size'=>$sl['size']));
				}
				$s_sls = array_count_values($s_sls);//已打包的信息集
                foreach ($packsku as $pku){
                	//获取该sku下的订单信息
                	foreach ($loglist as $sl){
                		if($sl['sku'] == $pku){
                			foreach (json_decode($sl['info']) as $v){
                				$o_sls[] = array('sku'=>$sl['sku'],'size'=>$v);//要进行打包的订单信息集
                			}
                		}
                	}
                	//看看已经打包了的该sku信息集和上面获取的该sku订单信息对比，然后确定该sku订单是否处理完
                	$f = true;//默认处理完
                	$count = 0;//计数器
                	foreach ($s_sls as $sk => $num){
                		if(json_decode($sk)->sku == $pku){//需要处理一个sku多个size的情况
                			$count+=1;
                		}
                		foreach ($o_sls as $vv){
                			if(json_decode($sk)->sku==$vv['sku'] && json_decode($sk)->size==$vv['size'][0]){
                				if($num < $vv['size'][1]){
                					$f = false;
                				}
                			}
                		}
                	}
                	if($count < count($o_sls)){
                		$f = false;
                	}
                	$o_sls = array();
                	if($f){
                		$stocklog->update2(array('statu'=>4,),$orderid,$site,$pku);
                	}
                }
			}
		}
		
		$this->view->msg=$msg;
		$this->view->orderid=$orderid;
		$this->view->site=$site;
	}
	
	/**对进行过分拣的订单进行操作*/
	public function operAction()
	{
		$orderid = $this->getRequest()->getParam('orderid');
	    $site = $this->getRequest()->getParam('site');
		$sku = $this->getRequest()->getParam('sku');//提交过来可能要操作的sku
		$size = $this->getRequest()->getParam('size');//提交过来可能要操作的size
		$isArr = $this->getRequest()->getParam('isadd');//是否要操作
	    $addtime = $this->getRequest()->getParam('addtime');
	    
	    $msg = array();
	    if(empty($orderid) || empty($site)){
	    	$msg[] = '订单号检测出错，请重新打包';
	    }
	    
		/**已打包/已操作的分拣不能操作，扫描错的也不可以操作，只有未处理的分拣才可以操作*/
		$stocklog = App_Model::factory('StockLog');//网站订单日志模型
		$sortlog = App_Model::factory('OrderSortLog');//订单分拣日志模型
		$sortloglist = $sortlog->getSortLog(array('order_id'=>$orderid,'site'=>$site,'statu'=>0))->toarray();//取出状态为0的项，即未处理的项
		
		if(empty($sortloglist)){
			$msg[] = '未发现有未处理的分拣，请返回重新确认操作';
		}
		
		$packid = array();//存放扫描正确的项对应的订单分拣日志id
		$packsku = array();//存放扫描正确的项对应的订单分拣日志sku
		$tempSortloglist = $sortloglist;
		$counter = 0;//计数器，用来计数判别是否有提交错误的扫描项
		foreach($isArr as $k){
			/**获取要进行操作的分拣id*/
			foreach ($sortloglist as $key => $sort){
				if(($sku[$k] == $sort['sku']) && ($size[$k] == $sort['size'])){
					$packid[] = $sort['id'];
					$packsku[] = $sort['sku'];
					unset($sortloglist[$key]);//要删除数组项是因为可能存在的已分拣项都是同一sku和id的
					break;
				}
			}
			/**看看是否有提交错误的扫描项，这些项是不能操作的*/
			foreach ($tempSortloglist as $sort2){
				if(!($sku[$k]==$sort2['sku'] && $size[$k]==$sort2['size'])){
					$counter += 1;
				}
			}
			if($counter == count($tempSortloglist)){
				$error = '操作失败，存在错误的扫描项，请检查并重新扫描';
			}
			$counter = 0;//计数器归0
		}
		if (!empty($error)){
			$msg[] = $error;
		}
			
		/**如果存在错误，操作不成功*/
		if(empty($msg)){
			$db = App_Db::localDb();
			$db->beginTransaction();
			try {
				foreach ($packid as $pk=>$id){
					$slitem = $stocklog->getStockLog(array('order_id'=>$orderid,'site'=>$site,'sku'=>$packsku[$pk]))->toarray();
					$row = array('oper_time'=>$addtime[$k],'operuser'=>$_SESSION['User']['user']['user_name'],'statu'=>'1',);//状态1为已操作，未打包
					$sortlog->update($row, $id);//更新订单分拣日志
					if($slitem[0]['statu'] == '2'){
						$stocklog->update2(array('statu'=>3,),$orderid,$site,$packsku[$pk]);//单独更新网站订单日志
					}
				}
				
				$db->commit();
				$this->view->ms='success';
			} catch (Exception $e) {
				$db->rollback();
				$this->view->ms='fail';
			}
		}
		
		$this->view->msg=$msg;
		$this->view->orderid=$orderid;
		$this->view->site=$site;
	}
	
	//订单分拣日志
	public function sortlogAction()
	{
        $log = App_Model::factory('OrderSortLog');
        
        /**取出搜索表单或者分页链接提交过来的数据*/
        $page = $this->getRequest()->getParam('page',1);
        $orderid = $this->getRequest()->getParam('orderid');
        $sku = $this->getRequest()->getParam('sku');
        $statu = $this->getRequest()->getParam('statu','');
        $site = $this->getRequest()->getParam('site');
        $starttime = $this->getRequest()->getParam('starttime');
        $endtime = $this->getRequest()->getParam('endtime');
        
        $pageNum = 10;//每页显示条数
       	$logList = $log->listAll($orderid,$sku,$statu,$site,$starttime,$endtime,$page, $pageNum)->toArray();
        /**将相应的值分配到视图调用*/
       	$this->view->logList = $logList;
        $this->view->orderid = $orderid;
        $this->view->sku = $sku;
        $this->view->site = $site;
        $this->view->statu = $statu;
        $this->view->starttime = $starttime;
        $this->view->endtime = $endtime;
        
        /**生成分页对象*/
		$num = $log->getTotalNum($orderid,$sku,$statu,$site,$starttime,$endtime);
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($num));
        $paginator->setItemCountPerPage($pageNum);
        $paginator->setCurrentPageNumber($page); 
        $this->view->paginator = $paginator ;
	}

	//操作日志
	public function operlogAction()
	{
        $log = App_Model::factory('OrderSortLog');
        
        /**取出搜索表单或者分页链接提交过来的数据*/
        $page = $this->getRequest()->getParam('page',1);
        $orderid = $this->getRequest()->getParam('orderid');
        $sku = $this->getRequest()->getParam('sku');
        $statu = 1;
        $site = $this->getRequest()->getParam('site');
        $starttime = $this->getRequest()->getParam('starttime');
        $endtime = $this->getRequest()->getParam('endtime');
        
        $pageNum = 10;//每页显示条数
       	$logList = $log->listAll($orderid,$sku,$statu,$site,$starttime,$endtime,$page, $pageNum)->toArray();
        /**将相应的值分配到视图调用*/
       	$this->view->logList = $logList;
        $this->view->orderid = $orderid;
        $this->view->sku = $sku;
        $this->view->site = $site;
        $this->view->starttime = $starttime;
        $this->view->endtime = $endtime;
        
        /**生成分页对象*/
		$num = $log->getTotalNum($orderid,$sku,$statu,$site,$starttime,$endtime);
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($num));
        $paginator->setItemCountPerPage($pageNum);
        $paginator->setCurrentPageNumber($page); 
        $this->view->paginator = $paginator ;
	}
	
	//打包日志
	public function packlogAction()
	{
        $log = App_Model::factory('StockExportLog');
        
        $page = $this->getRequest()->getParam('page',1);
        $billid = $this->getRequest()->getParam('billid');
        $orderid = $this->getRequest()->getParam('orderid');
        $site = $this->getRequest()->getParam('site');
        $starttime = $this->getRequest()->getParam('starttime');
        $endtime = $this->getRequest()->getParam('endtime');
        
        $pageNum = 10;//每页显示条数
       	$logList = $log->listAll($billid, $orderid, $site, $starttime, $endtime, $page, $pageNum)->toArray();
        /**将相应的值分配到视图调用*/
       	$this->view->logList = $logList;
        $this->view->billid = $billid;
        $this->view->orderid = $orderid;
        $this->view->site = $site;
        $this->view->starttime = $starttime;
        $this->view->endtime = $endtime;
        
        /**生成分页对象*/
		$num = $log->getTotalNum($billid, $orderid, $site,$starttime, $endtime);
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($num));
        $paginator->setItemCountPerPage($pageNum);
        $paginator->setCurrentPageNumber($page); 
        $this->view->paginator = $paginator ;
	}
	
	/**做单出货显示列表*/
	public function makelistAction()
	{
        $orderlog = App_Model::factory('OrderLog');
        
        $page = $this->getRequest()->getParam('page',1);
        $orderid = $this->getRequest()->getParam('orderid');
        $site = $this->getRequest()->getParam('site');
        $statu = $this->getRequest()->getParam('statu');
        $starttime = $this->getRequest()->getParam('starttime');
        $endtime = $this->getRequest()->getParam('endtime');
        
        /**根据条件获取OrderLog模型集合，然后转换成数组*/
        $pageNum = 15;//每页显示条数
       	$logList = $orderlog->listAll($orderid,$site,$statu,$starttime,$endtime,$page,$pageNum);
        $logList=$logList->toArray();
       	
        /**将相应的值分配到视图调用*/
       	$this->view->logList = $logList;
        $this->view->orderid = $orderid;
        $this->view->site = $site;
        $this->view->statu = $statu;
        $this->view->starttime = $starttime;
        $this->view->endtime = $endtime;
        
        /**生成分页对象*/
		$num = $orderlog->getTotalNum($orderid,$site,$statu,$starttime,$endtime);
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($num));
        $paginator->setItemCountPerPage($pageNum);
        $paginator->setCurrentPageNumber($page); 
        $this->view->paginator = $paginator ;
	}
	
	/**做出货单*/
	public function printlistAction()
	{
		$this->getHelper('layout')->setLayout('nolayout');
        $orderlogModel = App_Model::factory('OrderLog');
        $stocklogModel = App_Model::factory('StockLog');
        $buyerModel = App_Model::factory('Buyer');
        $isPrint = $this->getRequest()->getParam('isprint');
        $print = array();
        foreach($isPrint as $v){
        	$orderlog = $orderlogModel->getOne($v)->toArray();
        	$stocklog = $stocklogModel->getStockLog(array('order_id'=>$orderlog['order_id'],'site'=>$orderlog['site']))->toArray();
        	$buyer = $buyerModel->getBuyer(array('order_log_id'=>$orderlog['id']))->toArray();
        	$print[] = array('orderlog'=>$orderlog,'stocklog'=>$stocklog,'buyer'=>$buyer[0]);
        }
        //dump($print);
        $this->view->printlist = $print ;
        
		/**$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();//禁用layout
		$isPrint = $this->getRequest()->getParam('isprint');
		$str = '<head><meta charset="utf-8"></meta><link href="/include/bootstrapadmin/css/style.default.css" rel="stylesheet"></link><style>body{background-color: #FFFFFF;}</style></head>';
		foreach($isPrint as $k){
			$str = $str . "<iframe scrolling='no' height='100%' width='100%' frameborder='0' style='display:block;' src='".$this->getHelper('url')->url(array('controller'=>'log','action'=>'createlist','id'=>$k,))."'></iframe>";
		}
		echo $str;exit();*/
	}
	
	/**打印选中的出货单*/
	public function createlistAction()
	{
		$this->getHelper('layout')->setLayout('emptylayout');//禁用layout
		$id = $this->getRequest()->getParam('id');
        $orderlogModel = App_Model::factory('OrderLog');
        $stocklogModel = App_Model::factory('StockLog');
        $buyerModel = App_Model::factory('Buyer');
        $print = array();
		if(!empty($id)){
			$orderlog = $orderlogModel->getOne($id)->toArray();
			$stocklog = $stocklogModel->getStockLog(array('order_id'=>$orderlog['order_id'],'site'=>$orderlog['site']))->toArray();
			$buyer = $buyerModel->getBuyer(array('order_log_id'=>$orderlog['id']))->toArray();
			$print = array('orderlog'=>$orderlog,'stocklog'=>$stocklog,'buyer'=>$buyer[0]);
		}
		$this->view->print = $print;
	}
	
	/**报货日志*/
	public function baohuoAction()
	{
        $log = App_Model::factory('BaohuoLog');

        $page = $this->getRequest()->getParam('page',1);
        $starttime = $this->getRequest()->getParam('starttime');
        $endtime = $this->getRequest()->getParam('endtime');
        
        $pageNum = 50;//每页显示条数
        $logList = $log->listAll($starttime, $endtime, $page, $pageNum)->toArray();
        
        /**将相应的值分配到视图调用*/
        $this->view->logList = $logList;
        $this->view->starttime = $starttime;
        $this->view->endtime = $endtime;
        
        /**生成分页对象*/
        $num = $log->getTotalNum($starttime,$endtime);
        $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($num));
        $paginator->setItemCountPerPage($pageNum);
        $paginator->setCurrentPageNumber($page);
        $this->view->paginator = $paginator ;
	}
	
	/**异步删除报货日志*/
	public function deletebhAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		$id = $this->getRequest()->getParam('id', 0);
		$id = intval($id);
		if($id!=0){
			$baohuo = App_Model::factory('BaohuoLog');
			
			if($baohuo->delete($id)){
				echo 1;
			}else{
				echo 0;
			}
		}
	}
	
	/**每日日报的搜索产品时异步加载对应的信息*/
	public function loadskuAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$title = $this->getRequest()->getParam('title', '');
        $stock = App_Model::factory('Stock');
        $stockvalue = App_Model::factory('StockValue');
        $loglist = $stock->listAll($title,'','',1,20)->toArray();

        if(empty($loglist)){
        	echo json_encode(array('flag'=>'success'));
        }else{
        	$content = "";
        	foreach ($loglist as $v){
                $stockvaluelist = $stockvalue->getBySku($v['sku'])->toArray();
        		$content = $content.'<tr><td class="input-select"><input checked="checked" type="checkbox" name="isprint[]" value="'.$v['stock_id'].'">选择</td>';
        		$content = $content.'<td><input type="hidden" name="sku[]" value="'.$v['sku'].'">'.$v['sku'].'</td>';
        		$content = $content.'<td><input type="hidden" name="title[]" value="'.$v['title'].'">'.$v['title'].'</td>';
        		$content = $content.'<td class="sizenum"><span class="text"></span>';
        		foreach ($stockvaluelist as $vv){
        			$content = $content.'<div class="form-inline"><input readonly="readonly" class="form-control size" type="text" value="'.$vv['size'].'"><input class="form-control num" type="text" value="0" name="sizenum['.$v['sku'].']['.$vv['size'].']'.'"></div>';
        		}
        		$content = $content.'</td><td class="memo"><input name="memo['.$v['sku'].']" class="form-control memo" type="text"></td></tr>';
        	}
        	echo json_encode(array('content'=>$content,'flag'=>'success'));
        }
	}
	
	/**每日报货*/
	public function dailybaohuoAction()
	{
		$sizenum = $this->getRequest()->getParam('sizenum', '');
		$memo = $this->getRequest()->getParam('memo', '');
		if(!empty($sizenum)){
			$bhlog = App_Model::factory('BaohuoLog');
			$stock = App_Model::factory('Stock');

			$db = App_Db::localDb();
			$db->beginTransaction();
			try {
				foreach ($sizenum as $sku=>$sv){
					$info = array();
					foreach ($sv as $size=>$num){
						if(intval($num) <= 0){
							
						}else{
							$info[] = array($size,intval($num));
						}
					}
					if(!empty($info)){
					    $st = $stock->getBySku($sku)->toArray();
					    $row = array('sku'=>$sku,'title'=>$st[0]['title'],'info'=>json_encode($info),'memo'=>$memo[$sku],'add_time'=>date('Y-m-d H:i:s', time()),'add_user'=>$_SESSION['User']['user']['user_name']);
					    $bhlog->add($row);
					}
				}
				
				$db->commit();
				$this->view->msg='success';
			} catch (Exception $e) {
				$db->rollback();
				$this->view->msg='fail';
			}
		}
	}
	
}